package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 李旭
 * @date 2021/12/4 14:41
 * @Description:
 *
 *   支付宝管理
 *
 */
@Service
public class AlipayServiceImpl implements AlipayService {


    @Autowired
    private PaymentInfoService paymentInfoService;//
    @Autowired
    private AlipayClient alipayClient;


    //获取二维码支付页面   统一收单下单并支付页面接口
    @Override
    public String submit(Long orderId) {
        //1:生成支付表 （所有支付方式 共用的步骤） 提取
        PaymentInfo paymentInfo = paymentInfoService.
                insertPaymentInfo(orderId, PaymentType.ALIPAY);
        //2:获取二维码支付页面(由支付宝公司提供）
        //请求参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(AlipayConfig.notify_payment_url);//异步回调  通知商家的
        request.setReturnUrl(AlipayConfig.return_payment_url);//同步回调  通知消费者
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", paymentInfo.getOutTradeNo());//atguigu1638321708734999
        bizContent.put("total_amount", paymentInfo.getTotalAmount());
        bizContent.put("subject", paymentInfo.getSubject());
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");//快速即时贸易支付
        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        //显示响应体内容  二维码
        return response.getBody();
    }
    //统一收单交易退款接口
    //统一收单交易退款查询接口
}
